package com.cn.auth.jwt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

import java.util.Base64;
import java.util.Map;

/**
 * @Author SHANGGUAN
 **/

@Builder
@AllArgsConstructor
public class JwtHeader implements JwtBaseEncrypt {

    /**
     * 算法
     */
    @Getter
    @Builder.Default
    private String alg="HS256";
    /**
     * typ （类型）
     */
    @Getter
    @Builder.Default
    private String typ = "JWT";

    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final Base64.Decoder decoder = Base64.getDecoder();

    public String header() {
        return JSON.toJSONString(this);
    }

    /**
     * 通过Base64编码生成JwtHeader
     *
     * @return {@link String }
     */
    @Override
    public String encrypt() {
        return encoder.encodeToString(header().getBytes());
    }

    @Override
    public String decrypt(String encrypted) {
        byte[] decode = decoder.decode(encrypted);
        return new String(decode);
    }

    @SuppressWarnings("all")
    public static JwtHeader of(String headerBase64) {
        byte[] decode = decoder.decode(headerBase64);
        String jsonString = JSON.toJSONString(new String(decode));
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> javaMap = JSON.to(Map.class, jsonObject);
        return of(javaMap);
    }
    /**
     * 将Map转化为JwtHeader
     *
     * @param map 地图
     * @return {@link JwtPayLoad }
     */
    public static JwtHeader of(Map<String, Object> map) {
        JwtHeaderBuilder builder = JwtHeader.builder();
        Object alg = map.get("alg");
        Object typ = map.get("typ");
        if (alg != null) builder.alg(alg.toString());
        if (typ != null) builder.typ(typ.toString());
        return builder.build();
    }


}
